<?php

namespace Summer\Shop\Http\Controllers;

use Illuminate\Routing\Controller;
use RLuders\JWTAuth\Classes\JWTAuth;
use Input;
use Exception;
use Db;
use Summer\Hub\Http\Controllers\Traits\ApiReturn;
use Summer\Shop\Models\CartModel;
use Summer\Shop\Models\ProductModel;

class CartController extends Controller
{
    use ApiReturn;

    /**
     * 删除购物车
     * shopro版本的接口修改购物车根据act来去掉还是删除
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }

        $cart_ids=Input::get('cart_ids');
        if(!$cart_ids){
            return $this->apiError('参数错误');
        }
        CartModel::whereIn('id',$cart_ids)->where('user_id',$user->id)->delete();
        return $this->apiSuccess('操作成功');
    }
    /**
     * 更新购物车
     * @param JWTAuth $auth
     * @param DoUpdateCartRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \RLuders\JWTAuth\Exceptions\JsonValidationException
     */
    public function update(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $cart_id=Input::get('cart_id');
        $quantity=Input::get('quantity');
        $cart=CartModel::where('id',$cart_id)->first();
        if(!$cart||$cart->user_id!=$user->id){
            return $this->apiError('参数错误');
        }
        $cart->quantity=$quantity;
        $cart->total=$cart->price*$quantity;
        $cart->save();
        return $this->apiSuccess('操作成功');
    }

    /**
     * 购物车列表
     */
    public function index(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $page_size=Input::get('page_size')??20;
        $page=Input::get('page')??1;

        $query=CartModel::select();
        $query->where('user_id',$user->id);
        $records=$query->paginate($page_size,$page);
        $records->each(function ($record){
            $record->thumb=url('/storage/app/'.$record->thumb);
        });
        $rdata['records']=$records;
        return $this->apiSuccess('操作成功',$rdata);

    }

    /**
     * 添加购物车
     * @param JWTAuth $auth
     * @param DoAddToCartRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \RLuders\JWTAuth\Exceptions\JsonValidationException
     */
    public function addToCart(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $goods_list=Input::get('goods_list');
        $product_id=$goods_list[0]['product_id'];
        $quantity=$goods_list[0]['quantity'];
        $options_index=$goods_list[0]['options_index'];

        $optionsIndex = $this->parseOptions($options_index);
        $product=ProductModel::with(['image_preview'])->where('id',$product_id)->first();
        $price=$product->price;
        $description='';
        if($product->is_with_variants){
            foreach ($product->variants as $variant) {
                $id = $variant['id'];
                $optionVal = null;

                if(array_key_exists($id, $optionsIndex) && !empty($optionsIndex[$id])){
                    $optionVal = $optionsIndex[$id];
                }
                if($optionVal == null && !$variant['optional']){
                    return $this->apiError('请选择'.$variant['variant']);
                }

                foreach ($variant['items'] as $viv){
                    if($optionVal==$viv['ref']){
                        if($description){
                            $description.=",".$variant['variant'].":".$viv['val'];
                        }else{
                            $description=$variant['variant'].":".$viv['val'];
                        }
                        if($viv['price']){
                            $price=bcadd($price,$viv['price'],2);
                        }
                    }
                }
            }
        }

        $this->addItem($user, $product, $description, $price, $quantity, $options_index);

        return $this->apiSuccess('操作成功');
    }

    public function addItem($user, $product, $description, $price, $quantity, $index = null){
        $total = floatval($price) * intval($quantity);
        $cart=CartModel::where('user_id',$user->id)->where('product_id',$product->id)->where('index',$index)->first();
        if($cart){
            $cart->quantity+=$quantity;
            $cart->total+=$total;
        }else{
            $cart=new CartModel();
            $cart->user_id=$user->id;
            $cart->product_id=$product->id;
            $cart->index=$index;
            $cart->description=$description;
            $cart->title=$product->name;
            $cart->price=$price;
            $cart->quantity=$quantity;
            $cart->total=$total;
            $cart->thumb=$product->image_preview->getDiskPath();
            $cart->save();
        }
        return $cart;
    }

    protected function parseOptions($option_index){
        $option_index = explode(',', $option_index);
        $options = [];

        foreach ($option_index as $el) {
            if(empty($el))
                continue;

            $el = explode('::', $el);
            $options[$el[0]] = $el[1];
        }

        return $options;
    }

}
